local file = io.open(arg[1],"w+");
local bin_f = io.open(arg[2],"rb");

local write_pos = write_pos or 0;
local pc_addr = pc_addr or 0;

assert(file);
assert(bin_f);

local bin = bin_f:read('*a');
local len = #bin;

local read_u8 = function(offset)
    if(offset>=len)then return 0; end
    return bin:byte(offset+1);
end

local read_u16 = function(offset)
    return read_u8(offset)+read_u8(offset+1)*0x100;
end

local read_u32 = function(offset)
    return read_u16(offset)+read_u16(offset+2)*0x10000;
end

file:write('init\n');
file:write('reset halt\n');

for pos=0,len-1,4 do
    local w_pos = pos + write_pos;
    file:write(string.format('mww 0x%08x 0x%08x\n',w_pos,read_u32(pos)));
end

--有关PC地址是 set pc_addr [mrw 0x1fff8004]
--file:write(string.format('set_reg {pc 0x%08x}\n',pc_addr));
local s = [[
set pc_addr [mrw 0x1fff8004]
set pc_cmd [format "set_reg {pc 0x%08x}" $pc_addr]
eval $pc_cmd

]]

file:write(s);

file:close();
bin_f:close();